import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Drawer, message, Col, Row,DatePicker, Tag  } from 'antd';
import type { DatePickerProps } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from '@umijs/max';
import type { FormValueType } from './components/UpdateForm';
import type { TableListItem, TableListPagination} from './data';
import type { RangePickerProps } from 'antd/es/date-picker/generatePicker';
import { getTimeDistance } from './utils/utils';
import dayjs from 'dayjs';
import {getTalentList, checkTalent, getPublicTime, publicForm, updateRule } from './service';
import moment from 'moment';
import ExcelJS from 'exceljs'
const { RangePicker } = DatePicker;
type RangePickerValue = RangePickerProps<dayjs.Dayjs>['value'];
/**
 * 添加节点
 *
 * @param fields
 */

/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields: FormValueType, currentRow?: TableListItem) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleExportExcel = async ()=>{
  const res = await getTalentList({current: 1, pageSize: 999999999 })
  if(res.data){
    // 获取并转换数据
    const {data = []} = res;
    const rawsData = []
    console.log(data)
    let seq = 1
    for(const i in data){
      const transData = []
      // 序号
      transData.push(seq)
      seq += 1
      // 主管单位（地区）
      transData.push(data[i]["organizer"])
      // 用人单位
      transData.push(data[i]["employer"])
      // 项目名称
      transData.push(data[i]["name"])
      // 项目简介
      transData.push(data[i]["introduction"])
      // 项目层次
      switch (data[i]['level']){
        case 1:
          transData.push('高层次');
          break;
        case 2:
          transData.push('中等层次');
          break;
        default:
          transData.push('');
      }
      // 项目领域
      switch (data[i]['field']){
        case 1:
          transData.push('重大战略基础前沿');
          break;
        case 2:
          transData.push('空间技术');
          break;
        case 3:
            transData.push('能源');
            break;
        case 4:
          transData.push('能源');
          break;
        case 5:
            transData.push('交通');
            break;
        case 6:
          transData.push('资源环境');
          break;
        case 7:
          transData.push('信息技术');
          break;
        case 8:
          transData.push('生物医药与卫生健康');
          break;
        case 9:
          transData.push('文化旅游');
          break;
        case 10:
          transData.push('制造');
          break;
        case 11:
          transData.push('社会事业与公共安全');
          break;
        case 12:
          transData.push('材料');
          break;
        case 13:
          transData.push('其他');
          break;
        default:
          transData.push('');
      }
      // 项目来源
      switch (data[i]['source']){
        case 1:
          transData.push('省内');
          break;
        case 2:
          transData.push('省外');
          break;
        default:
          transData.push('');
      }
      // 是否为重点项目
      switch (data[i]['isKey']){
        case true:
          transData.push('是');
          break;
        case false:
          transData.push('否');
          break;
        default:
          transData.push('');
      }
      // 是否现场签约
      switch (data[i]['isSign']){
        case true:
          transData.push('是');
          break;
        case false:
          transData.push('否');
          break;
        default:
          transData.push('');
      }
      // 项目类别
      switch (data[i]['category']){
        case 1:
          transData.push('团队');
          break;
        case 2:
          transData.push('个人');
          break;
        default:
          transData.push('');
      }
      // 意向合作单位（团队、个人）基本情况
      transData.push(data[i]["situation"])
      // 意向合作方式
      switch (data[i]['category']){
        case 1:
          transData.push('项目引才');
          break;
        case 2:
          transData.push('兼职引才');
          break;
        case 3:
          transData.push('飞地用才');
          break;
        case 4:
          transData.push('顾问指导');
          break;
        case 5:
          transData.push('挂职引进');
          break;
        case 6:
          transData.push('退休特聘');
          break;
        case 7:
          transData.push('其他');
          break;
        default:
          transData.push('');
      }
      // 进展情况
      switch (data[i]['progress']){
        case 1:
          transData.push('成功对接');
          break;
        case 2:
          transData.push('正在对接');
          break;
        case 3:
          transData.push('尚未对接');
          break;
        case 4:
          transData.push('需帮助对接');
          break;
        default:
          transData.push('');
      }
      // 是否邀请参加洽谈会
      switch (data[i]['isMeeting']){
        case true:
          transData.push('是');
          break;
        case false:
          transData.push('否');
          break;
        default:
          transData.push('');
      }
      // 联系人及联系方式
      transData.push(`${data[i]['contactName']}${data[i]['telephone']}`)
      // 备注
      transData.push(`${data[i]['remark']}`)
      // 审批状态
      switch (data[i]['state']){
        case 0:
          transData.push('待审批');
          break;
        case 1:
          transData.push('审批通过');
          break;
        case 2:
          transData.push('审批未通过');
          break;
        default:
          transData.push('');
      }
      rawsData.push(transData)
    }


    const sheetName = '人才项目'
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('Sheet1')
    // 将表格添加到工作表
    worksheet.addTable({
      name: 'MyTable',
      ref: 'A1',
      headerRow: true,
      columns: [
        {name: '序号'},
        {name: '主管单位（地区）'},
        {name: '用人单位'},
        {name: '项目名称'},
        {name: '项目简介'},
        {name: '项目层次'},
        {name: '项目领域'},
        {name: '项目来源'},
        {name: '是否为重点项目'},
        {name: '是否现场签约'},
        {name: '项目类别'},
        {name: '意向合作单位（团队、个人）基本情况'},
        {name: '意向合作方式'},
        {name: '进展情况'},
        {name: '是否邀请参加洽谈会'},
        {name: '联系人及联系方式'},
        {name: '备注'},
        {name: '审批状态'},
      ],
      rows: rawsData
    });

    const writeFile = (fileName, content) => {
      const link = document.createElement("a");
      const blob = new Blob([content], {
        type: "application/vnd.ms-excel;charset=utf-8;"
      });
      link.download = fileName;
      link.href = URL.createObjectURL(blob);
      link.click();
    };

    // 表格的数据绘制完成，定义下载方法，将数据导出到Excel文件
    workbook.xlsx.writeBuffer().then((buffer) => {
      writeFile(sheetName, buffer);
    });
  }else{
    message.error('出错啦！')
  }
}


const TableList: React.FC = () => {
  const [checkModalVisible, setCheckModalVisible] = useState<boolean>(false);
  const [responseModelVisible, setResponseModelVisuble] = useState<boolean>(false);
  const [formState, setFormState] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem | undefined>(undefined);
  const [rangePickerValue, setRangePickerValue] = useState<RangePickerValue>(
    getTimeDistance('year'),
  );

  const handleGetPublickTime = async ()=>{
    const res = await getPublicTime();
    if(res.data){
      const {startTime, endTime, state} = res.data || {};
      setRangePickerValue([dayjs.unix(startTime), dayjs.unix(endTime)]);
      setFormState(state);

    }
  }
  useEffect(()=>{
    handleGetPublickTime()
  },[])

  const onChange = (
    value: DatePickerProps['value'] | RangePickerProps['value'],
    dateString: [string, string] | string,
  ) => {
    console.log('Selected Time: ', value);
    console.log('Formatted Selected Time: ', dateString);
  };
  
  const onOk = (value: DatePickerProps['value'] | RangePickerProps['value']) => {
    setRangePickerValue(value)
  };


  const handleCheckSuccess = async (id: string, state: number,)=>{
    const response = ''
    const res = await checkTalent({id, state, response});
      if(res.data){
        setCheckModalVisible(false);
        message.success('审批完成')
        actionRef.current?.reload();
        setCurrentRow(undefined);
        setShowDetail(false);
      }else{
        setCheckModalVisible(false);
        message.error(res.message)
        actionRef.current?.reload();
        setCurrentRow(undefined);
        setShowDetail(false);
      }
  }

  const handleCheckFail = async (id: string, state: number, response: string)=>{
    const res = await checkTalent({id, state, response});
    if(res.data){
      setCheckModalVisible(false);
      message.success('审批完成')
      actionRef.current?.reload();
      setCurrentRow(undefined);
      setShowDetail(false);
      setResponseModelVisuble(false);
    }else{
      setCheckModalVisible(false);
      message.error(res.message)
      actionRef.current?.reload();
      setCurrentRow(undefined);
      setShowDetail(false);
      setResponseModelVisuble(false);
    }
  }

  const handlePublicForm = async ()=>{
    const startTime = moment(rangePickerValue[0]).unix()
    const endTime = moment(rangePickerValue[1]).unix()
    if(startTime > endTime){
      message.error('结束时间不能早于开始时间');
      return;
    }
    const res = await publicForm({startTime, endTime, state: true})
    if(res.data){
      message.success('发布成功')
      setFormState(true)
    }else{
      message.error(res.message)
    }
  }

  const handleCloseForm = async ()=>{
    const res = await publicForm({state: false})
    if(res.data){
      message.success('问卷已停止')
      setFormState(false)
    }else{
      message.error(res.message)
    }
  }
  /** 国际化配置 */

  const columns: ProColumns<TableListItem>[] = [
    {
      title: 'id',
      hidden: true,
      hideInSearch: true,
      // hideInSearch: true,
      dataIndex: '_id',
    },
    {
      title: '项目名称',
      // hideInSearch: true,
      dataIndex: 'name',
    },
    {
      title: '主管单位',
      // hideInSearch: true,
      dataIndex: 'organizer',
    },
    {
      title: '用人单位',
      // hideInSearch: true,
      dataIndex: 'employer',
    },
    {
      title: '提交时间',
      dataIndex: 'submitTime',
      valueType: 'dateTime',
    },
    {
      title: '审批状态',
      dataIndex: 'state',
      valueEnum: {
        0: "待审批",
        1: "通过",
        2: "不通过",
      },
      render: (_, { state }) => (
        <>
          <Tag color={state === 0 ? 'blue': state === 1 ? 'green':'red'} key={state} style={{fontSize: 15}}>
            {state === 0 ? '待审批': state === 1 ? '审批通过':'审批不通过'}
          </Tag>
        </>
      ),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="detail"
          onClick={() => {
            console.log(record)
            setCurrentRow(record);
            setShowDetail(true)
            // handleUpdateModalVisible(true);
          }}
        >
          审批
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <Row
          gutter={1}
          style={{
            marginTop: 24,
            marginBottom: 24
          }}
        >
          <Col xl={8} lg={24} md={24} sm={24} xs={24}>
            <RangePicker
              value={rangePickerValue}
              showTime={{ format: 'HH:mm' }}
              format="YYYY-MM-DD HH:mm"
              onChange={onChange}
              onOk={onOk}
              disabled={formState}
            />
          </Col>
          <Col xl={8} lg={24} md={24} sm={24} xs={24}>
            {formState ? 
              <Button
                // type="primary"
                key="close"
                onClick={() => {
                  handleCloseForm()
                }}
              >
                停止问卷
              </Button>:
              <Button
                type="primary"
                key="open"
                onClick={() => {
                  handlePublicForm()
                }}
              >
                发布问卷
              </Button>}
          </Col>
        </Row>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        pagination={{
          showSizeChanger: true
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleExportExcel()
            }}
          >
            导出excel
          </Button>,
        ]}
        request={getTalentList}
        columns={columns}
      />
      <ModalForm
        title="审批意见"
        width="400px"
        modalProps={{destroyOnClose: true}}
        open={responseModelVisible}
        onVisibleChange={setResponseModelVisuble}
        onFinish={async (value)=>{
          handleCheckFail(currentRow?._id, 2,value.desc);
        }}
      >
        <ProFormTextArea 
          width="md" 
          name="desc" 
          rules={[
            {
              required: true,
              message: '规则名称为必填项',
            }]}
        />
      </ModalForm>

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        <ProDescriptions<TableListItem>
          column={1}
          title={currentRow?.name}
          request={async () => ({
            data: currentRow || {},
          })}
          params={{
            id: currentRow?.name,
          }}
          // columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          columns={[
            {
              title: '项目名称',
              dataIndex: 'name',
            },
            {
              title: '主管地区（单位）',
              dataIndex: 'organizer',
            },
            {
              title: '用人单位',
              dataIndex: 'employer',
            },
            {
              title: '项目简介',
              dataIndex: 'introduction',
              valueType: 'textarea'
            },
            {
              title: '项目层次',
              dataIndex: 'level',
              valueEnum: {
                1: "高层次",
                2: "中等层次"
              },
            },
            {
              title: '项目领域',
              dataIndex: 'field',
              valueEnum: {
                1: "重大战略基础前沿",
                2: "空间技术",
                3: "能源",
                4: "农业",
                5: "交通",
                6: "资源环境",
                7: "信息技术",
                8: "生物医药与卫生健康",
                9: "文化旅游",
                10: "制造",
                11: "社会事业与公共安全",
                12: "材料",
              },
            },
            {
              title: '项目来源',
              dataIndex: 'source',
              valueEnum: {
                1: "省内",
                2: "省外"
              },
            },
            {
              title: '是否为重点项目',
              dataIndex: 'isKey',
              valueEnum: {
                true: "是",
                false: "否"
              },
            },
            {
              title: '是否现场签约',
              dataIndex: 'isSign',
              valueEnum: {
                true: "是",
                false: "否"
              },
            },
            {
              title: '项目类别',
              dataIndex: 'category',
              valueEnum: {
                1: "团队",
                2: "个人"
              },
            },
            {
              title: '意向合作单位（团队、个人）基本情况',
              dataIndex: 'category',
              valueType: 'textarea'
            },
            {
              title: '意向合作方式',
              dataIndex: 'cooperationMethod',
              valueEnum: {
                1: "项目引才",
                2: "兼职引才",
                3: "飞地用才",
                4: "顾问指导",
                5: "挂职引进",
                6: "退休特聘",
                7: "其他",
              },
            },
            {
              title: '进展情况',
              dataIndex: 'progress',
              valueEnum: {
                1: "成功对接",
                2: "正在对接",
                3: "尚未对接",
                4: "需帮助对接",
              },
            },
            {
              title: '是否邀请参加洽谈会',
              dataIndex: 'isMeeting',
              valueEnum: {
                true: "是",
                false: "否"
              },
            },
            {
              title: '联系人',
              dataIndex: 'contactName',
            },
            {
              title: '联系方式',
              dataIndex: 'telephone',
            },
            {
              title: '备注',
              dataIndex: 'remark',
              valueType: 'textarea'
            },
            {
              title: '提交时间',
              dataIndex: 'submitTime',
              hideInSearch: true,
              renderText: (text) => {
                if (text) {
                  return moment(text).format('YYYY-MM-DD HH:mm:ss');
                } else {
                  return null;
                }
              },
            },
            {
              title: '审批状态',
              dataIndex: 'state',
              valueEnum: {
                0: "待审批",
                1: "通过",
                2: "不通过",
              },
            },
            {
              title: '操作',
              dataIndex: 'option',
              valueType: 'option',
              render: (_, record) => [
                <a
                  key="success"
                  onClick={()=>{handleCheckSuccess(record._id, 1)}}
                >
                  审批通过
                </a>,
                <a
                  key="fail"
                  onClick={()=>{
                    setResponseModelVisuble(true);
                  }}
                >
                  审批不通过
                </a>,
              ],
            },
            {
              title: '审批意见',
              dataIndex: 'response',
            },
          ]}
        />
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
